package com.gingko.duominuo.network.download

import android.util.Log
import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback
import com.alibaba.sdk.android.oss.common.OSSLog
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider
import com.alibaba.sdk.android.oss.model.*
import com.gingko.duominuo.App
import com.gingko.duominuo.utils.logd
import java.io.File
import java.util.*


object OSSUpload {
    private const val scheme = "https://"
    private const val endpoint = "oss-cn-beijing.aliyuncs.com"
    private const val imagePath = "/image"
    private const val dataPath = "/data"
    private const val accessKeyId = "LTAI4FzizFy2cYUTEvMqJu4V"
    private const val accessKeySecret = "6OBWswb0Ob9AUAACPSr5RwZO1MyF8A"

    //https://alphacar-domino-test.oss-cn-beijing.aliyuncs.com/
    private const val bucketName = "alphacar-domino"

    const val RESOURCE_DATA_END_POINT = "$scheme$bucketName.$endpoint$dataPath"

    private lateinit var oss: OSSClient

    init {
        createOssClient()
//        createBucket()
    }


    private fun createOssClient() {
        // 配置类如果不设置，会有默认配置。
        val clientConfiguration = ClientConfiguration().apply {
            connectionTimeout = 15 * 1000 // 连接超时，默认15秒。
            socketTimeout = 15 * 1000 // socket超时，默认15秒。
            maxConcurrentRequest = 5 // 最大并发请求数，默认5个。
            maxErrorRetry = 2 // 失败后最大重试次数，默认2次。
        }
        // 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。
        val credentialProvider = OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret)
        OSSLog.enableLog()
        oss = OSSClient(App.instance, scheme + endpoint, credentialProvider, clientConfiguration)

    }

    private fun createBucket() {
        val createBucketRequest = CreateBucketRequest(bucketName)
        createBucketRequest.bucketACL = CannedAccessControlList.PublicRead
        createBucketRequest.locationConstraint = "oss-cn-beijing"
        val task = oss.asyncCreateBucket(createBucketRequest, object : OSSCompletedCallback<CreateBucketRequest, CreateBucketResult?> {
            override fun onSuccess(request: CreateBucketRequest, result: CreateBucketResult?) {
                Log.d("locationConstraint", request.locationConstraint)
            }

            override fun onFailure(request: CreateBucketRequest?, clientException: ClientException?, serviceException: ServiceException?) {
                // 请求异常。
                clientException?.printStackTrace()
                serviceException?.let {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.errorCode)
                    Log.e("RequestId", serviceException.requestId)
                    Log.e("HostId", serviceException.hostId)
                    Log.e("RawMessage", serviceException.rawMessage)
                }

            }
        })
        task.waitUntilFinished()
    }

    fun uploadFile(file: File, uploadCallback: UploadCallback) {
        val uuid = UUID.randomUUID().toString().replace("-", "")
        val suffixName: String = file.absolutePath.substring(file.absolutePath.lastIndexOf("."))
        val objectName: String = System.currentTimeMillis().toString() + uuid.substring(uuid.length - 10) + suffixName
        val objectRequest = PutObjectRequest(bucketName, "image/$objectName", file.absolutePath)
        // 异步上传时可以设置进度回调。
        objectRequest.progressCallback = OSSProgressCallback { request, currentSize, totalSize -> Log.d("PutObject", "currentSize: $currentSize totalSize: $totalSize") }
        oss.asyncPutObject(objectRequest,
            object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult) {
                    Log.d("PutObject", "UploadSuccess")
                    Log.d("ETag", result.eTag)
                    Log.d("RequestId", result.requestId)
                    "$scheme$bucketName.$endpoint/${objectRequest.objectKey}".logd("image url")
                    uploadCallback.onSuccess("$scheme$bucketName.$endpoint/${objectRequest.objectKey}")
                }

                override fun onFailure(request: PutObjectRequest?, clientException: ClientException?, serviceException: ServiceException?) {
                    if (clientException != null) {
                        // 服务异常。
                        clientException.printStackTrace()
                        uploadCallback.onFailure(clientException.message)
                    } else {
                        serviceException?.let {
                            Log.e("ErrorCode", serviceException.errorCode)
                            Log.e("RequestId", serviceException.requestId)
                            Log.e("HostId", serviceException.hostId)
                            Log.e("RawMessage", serviceException.rawMessage)
                            uploadCallback.onFailure(it.rawMessage)
                        }
                    }
                }


            })
    }


}